import { Component, OnInit } from '@angular/core';
import { ProblemNewService} from './new.component.service';
import {GlobalService} from "../../../../global.service";
import {User} from "../../../../user/model/user-model";
import {Router} from "@angular/router";
import { Location } from '@angular/common';
import { Response} from '@angular/http';
declare function editormd(string,any);

@Component({
  selector: 'app-new',
  templateUrl: './new.component.html',
  styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit {

  data:Problem=new Problem;
  testDataScore: any[] = [];
  currentUser:User;
  btnText:string;
  editor:any;
  editorHtml:string;
  api:any;

  constructor(
    private globalService:GlobalService,
    private problemNewService:ProblemNewService,
    private router:Router,
    private location:Location,

  ) { }

  ngOnInit() {
    this.api = this.globalService.api;
    let url = this.location.path();

    this.editor = editormd("test-editormd", {
      width   : "90%",
      height  : 640,
      syncScrolling : "single",
      path    : "assets/editor-md/lib/"
    });

    if(url.indexOf("type/6/new/")>0){
      let code =  url.substring(url.indexOf("type/6/new/")+11);
      this.problemNewService.findProblemByCode(code).subscribe((res:Response)=>{
        console.log("problem data: ",res.json());

        this.data.name = res.json().value.name;
        this.data.degree = res.json().value.degree;
        this.data.author = res.json().value.author;
        this.data.company = res.json().value.company;
        this.data.author = res.json().value.author;

        this.data.describe = res.json().value.describe;
        this.data.degree = res.json().value.degree;
        this.data.limitTime = res.json().value.limitTime;
        this.data.limitMoney = res.json().value.limitMoney;
        this.data.testDataCode = res.json().value.testDataCode;
        this.data.score = res.json().value.score;

        this.problemNewService.findTestData(res.json().value.testDataCode).subscribe((result:Response)=>{
          console.log("测试用例：",result.json());
          this.data.score = 0;
          for(let i=0;i<result.json().rows.length;i++){
            let item = result.json().rows[i];
            let data = (item+"").split("_");
            if(data.length==4){
              this.testDataScore.push({name:data[0],score:data[1],remark:data[2],date:data[3]});
            }else if(data.length==3){
              this.testDataScore.push({name:data[0],score:data[1],date:data[2]});
            }
            this.data.score += parseInt(data[1]);
          }
        });
        this.btnText = '保存';
      });
    }else{
      this.data.describe='\n这是一个编程题模板。请在这里写题目描述。例如：本题目要求读入2个整数A和B，然后输出它们的和。\n\n#### 输入格式：\n请在这里写输入格式。例如：输入在一行中给出2个绝对值不超过1000的整数A和B。\n\n#### 输出格式：\n请在这里描述输出格式。例如：对每一组输入，在一行中输出A+B的值。\n\n#### 输入样例:\n在这里给出一组输入。例如：\n```in\n18 -299\n```\n\n#### 输出样例:\n在这里给出相应的输出。例如\n```out \n-281\n```';
      this.data.degree=1;
      this.data.limitTime=400;
      this.data.limitMoney=64;
      this.data.score=0;

      this.btnText = "创建";
    }
    this.currentUser = this.globalService.getCurrentUser();
  }

  onPhotoUpload(event) {
    let _this = this;
    let response = JSON.parse(event.xhr.response);
    console.log(response);
    if(response.success){
      this.data.score = 0;
      this.testDataScore = [];
      this.data.testDataCode = response.msg.split("@")[1];
      response.rows.forEach(function (item) {
        let data = (item+"").split("_");
        if(data.length==4){
          _this.testDataScore.push({name:data[0],score:data[1],remark:data[2],date:data[3]});
        }else if(data.length==3){
          _this.testDataScore.push({name:data[0],score:data[1],date:data[2]});
        }
        _this.data.score += parseInt(data[1]);
        console.log("!!!!!!!"+_this.data.score);
      });
    }else{
      alert(response.msg);
    }
  }

  submit(){

    if(this.btnText=="保存"){
      this.data.code = this.location.path().substring(this.location.path().indexOf("type/6/new/")+11);
      this.data.properties.update = 'true';
    }else{
      this.data.properties.save = 'true';
    }
    this.data.creator = this.currentUser.code;
    this.data.describe = this.editor.getMarkdown();
    this.problemNewService.saveProblem(this.data).subscribe((res:Response)=>{
      console.log("receive data:",res.json());
      this.router.navigateByUrl("/problems/type/6")
    });

  }
}

class Problem {
  code:string;
  creator:string;
  name:any;
  degree:any;
  author:any;
  company:any;
  score:number=0;
  describe:any;
  limitTime:any;
  limitMoney:any;
  testDataCode:any;
  properties:Properties = new Properties;
}
class Properties {
  save:any;
  update:any;
}

